from django.test import TestCase
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from rest_framework import status
from .models import Chef, ChefReview

User = get_user_model()

class ChefTestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(
            email='test@example.com',
            password='testpass123',
            first_name='Test',
            last_name='User'
        )
        self.chef_user = User.objects.create_user(
            email='chef@example.com',
            password='chefpass123',
            first_name='Chef',
            last_name='Test',
            is_chef=True
        )
        self.chef = Chef.objects.create(
            user=self.chef_user,
            bio='Test bio',
            years_of_experience=5,
            specialty='Italian',
            address='123 Test St',
            city='Testville',
            state='TS',
            zip_code='12345'
        )

    def test_list_chefs(self):
        response = self.client.get('/api/chefs/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]['user']['first_name'], 'Chef')

    def test_chef_detail(self):
        response = self.client.get(f'/api/chefs/{self.chef.id}/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['user']['first_name'], 'Chef')
        self.assertEqual(response.data['specialty'], 'Italian')

    def test_create_review(self):
        self.client.force_authenticate(user=self.user)
        data = {
            'rating': 5,
            'comment': 'Great chef!'
        }
        response = self.client.post(f'/api/chefs/{self.chef.id}/reviews/', data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(ChefReview.objects.count(), 1)
        self.assertEqual(self.chef.reviews.count(), 1)
        
        # Check if chef rating was updated
        self.chef.refresh_from_db()
        self.assertEqual(self.chef.rating, 5)
        self.assertEqual(self.chef.review_count, 1)